package com.example.repair_service.service.impl;

import com.example.repair_service.entity.UserAddressEntity;
import com.example.repair_service.mapper.AddressMapper;
import com.example.repair_service.service.AddressService;
import com.example.repair_service.context.BaseContext;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;

    /**
     * 条件查询
     *
     * @param addressBook
     * @return
     */
    public List<UserAddressEntity> list(UserAddressEntity addressBook) {
        return addressMapper.list(addressBook);
    }

    /**
     * 新增地址
     *
     * @param address
     */
    public void save(UserAddressEntity address) {
        address.setUserId(BaseContext.getCurrentId());
        address.setIsDefault(false);
        addressMapper.insert(address);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    public UserAddressEntity getById(Long id) {
        UserAddressEntity address = addressMapper.getById(id);
        return address;
    }

    /**
     * 根据id修改地址
     *
     * @param addressBook
     */
    public void update(UserAddressEntity addressBook) {
        addressMapper.update(addressBook);
    }

    /**
     * 设置默认地址
     *
     * @param addressBook
     */
    @Transactional
    public void setDefault(UserAddressEntity addressBook) {
        //1、将当前用户的所有地址修改为非默认地址 update address_book set is_default = ? where user_id = ?
        addressBook.setIsDefault(false);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressMapper.updateIsDefaultByUserId(addressBook);

        //2、将当前地址改为默认地址 update address_book set is_default = ? where id = ?
        addressBook.setIsDefault(true);
        addressMapper.update(addressBook);
    }

    /**
     * 根据id删除地址
     *
     * @param id
     */
    public void deleteById(Long id) {
        addressMapper.deleteById(id);
    }

}
